/*
 * 网址查询
 */
#include "stdafx.h"
#include "url_query.h"
#include <string.h>
#include <mysql.h>
#include "config.h"
#include <time.h>

// Mysql变量
static MYSQL		mysql_conn;
static bool			is_mysql_init;

/*
 * 自定义时间格式化函数
 */
char* myctime(const time_t* tt, char* pt)
{
	struct tm		t		= {0};

	localtime_r(tt, &t);
	sprintf(pt, "%04d-%02d-%02d %02d:%02d:%02d", 
				t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
				t.tm_hour, t.tm_min, t.tm_sec);
	return pt;
}

/*
 * 连接到数据库
 */
inline MYSQL* url_connect_db()
{
	char		szhost[128]		= {0};
	char		szuser[128]		= {0};
	char		szpwd[128]		= {0};
	char		szdb[128]		= {0};

	if( is_mysql_init && 0 == mysql_ping(&mysql_conn) )
	{
		return &mysql_conn;
	}
	// 新连接数据库
	mysql_init(&mysql_conn);

	ini_get_mysql_host(szhost, sizeof(szhost) - 1);
	ini_get_mysql_user(szuser, sizeof(szuser) - 1);
	ini_get_mysql_pwd(szpwd, sizeof(szpwd) - 1);
	ini_get_mysql_database(szdb, sizeof(szdb) - 1);

	if( !mysql_real_connect(&mysql_conn, szhost, szuser, szpwd, szdb
					, 0, NULL, CLIENT_FOUND_ROWS) )
	{
		syslog(LOG_ERR, "mysql_real_connet failed: %s"
					, mysql_error(&mysql_conn));
		return NULL;
	}

	is_mysql_init = true;
	return &mysql_conn;
}
/*
 * 查询URL
 */
bool url_query(const char* purl, uint8_t* ptp1, uint8_t* ptp2,
		uint8_t* ptp3, uint8_t* prating)
{
	MYSQL*			mysql;
	char			domain[257]			= {0};
	char			sql[1024]			= {0};
	int				res;
	MYSQL_RES*		res_ptr				= NULL;
	MYSQL_ROW		row;
	bool			ret					= false;

	// 连接MYSQL
	mysql = url_connect_db();
	if(NULL == mysql)
	{
		return false;
	}
	// 查询SQL语句
	url_get_domain(purl, domain);
	snprintf(sql, sizeof(sql) - 1
				, "select typeid,typeid2,typeid3,rating from t_urltype where "
				"url='%s' and lasttime > now()"
				, domain);
	res = mysql_query(mysql, sql);
	if( res )
	{
		syslog(LOG_ERR, "mysql_query %s: %s", sql, mysql_error(mysql));
		return false;
	}
	// 获取返回值
	res_ptr = mysql_store_result(mysql);
	if(NULL == res_ptr)
	{
		return false;
	}
	row = mysql_fetch_row(res_ptr);
	if( row )
	{
		*ptp1 = atoi(row[0]);
		*ptp2 = atoi(row[1]);
		*ptp3 = atoi(row[2]);
		*prating = atoi(row[3]);
		ret = true;
	}
	mysql_free_result(res_ptr);
	return ret;
}

/*
 * 更新URL
 */
bool url_update(const char* purl, uint32_t tt, uint8_t tp1,
		uint8_t tp2, uint8_t tp3, uint8_t rating)
{
	MYSQL*		mysql;
	char		domain[257]		= {0};
	char		sql[1024]		= {0};
	char		ptime[64]		= {0};

	mysql = url_connect_db();
	if(NULL == mysql)
	{
		return false;
	}
	url_get_domain(purl, domain);
	myctime((time_t*)&tt, ptime);
	snprintf(sql, sizeof(sql) - 1, 
				"insert into t_urltype(url,typeid,typeid2,typeid3,rating,"
				"lasttime) values('%s',%d,%d,%d,%d,'%s') on duplicate key "
				"update typeid=%d,typeid2=%d,typeid3=%d,rating=%d,"
				"lasttime='%s'",
				domain, tp1, tp2, tp3, rating, ptime,
				tp1, tp2, tp3, rating, ptime);
	mysql_query(mysql, sql);
	return true;
}
